package top.lyjwn.ajui.widget.banner;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import top.lyjwn.ajui.R;
import top.lyjwn.ajui.adapter.BannerAdapter;
import top.lyjwn.ajui.adapter.BannerSingleAdapter;
import top.lyjwn.ajui.adapter.BannerDoubleAdapter;
import top.lyjwn.ajui.util.LogUtil;

/**
 * 轮播图
 *
 * @author luoyujie
 */
public class BannerView extends RelativeLayout {

    private Context context;
    private BannerAdapter baseAdapter;
    private RecyclerView banner_recycler_view;
    private BannerIndicator banner_indicator;
    private boolean isTouch = false;
    private SmoothLinearLayoutManager layoutManager;
    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    private boolean isDot = true;
    /**
     * 同时高亮的引导点
     */
    private int dotNum;

    public BannerView(Context context) {
        this(context, null);
    }

    public BannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        layoutManager = new SmoothLinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);

    }


    /**
     * @return
     */
    public BannerView init() {
        return init(1, null);
    }

    /**
     * @param dotNum 同时引导的数量
     * @return
     */
    public BannerView init(int dotNum) {
        return init(dotNum, null);
    }

    /**
     * @param listener 项点击事件
     * @return
     */
    public BannerView init(OnClickItemListener listener) {
        return init(1, listener);
    }


    /**
     * @param dotNum   引导点数量
     * @param listener 项点击事件
     * @return
     */
    public BannerView init(int dotNum, OnClickItemListener listener) {
        this.dotNum = dotNum;
        View view = LayoutInflater.from(context).inflate(R.layout.widget_banner, this);
        banner_recycler_view = view.findViewById(R.id.banner_recycler_view);
        banner_indicator = findViewById(R.id.banner_indicator);
        RecyclerView.Adapter adapter;
        if (dotNum == 1) {
            BannerSingleAdapter bannerSingleAdapter = new BannerSingleAdapter(context, listener);
            baseAdapter = bannerSingleAdapter;
            adapter = bannerSingleAdapter;
        } else {
            BannerDoubleAdapter bannerDoubleAdapter = new BannerDoubleAdapter(context, listener);
            baseAdapter = bannerDoubleAdapter;
            adapter = bannerDoubleAdapter;
        }
        banner_recycler_view.setLayoutManager(layoutManager);
        banner_recycler_view.setHasFixedSize(true);
        banner_recycler_view.setAdapter(adapter);
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(banner_recycler_view);
        banner_recycler_view.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                switch (e.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isTouch = true;
                        break;
                    case MotionEvent.ACTION_UP:
                        isTouch = false;
                        break;

                }
                return false;
            }

            @Override
            public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {


            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });
        return this;
    }

    /**
     * 写入项
     *
     * @param items
     */
    public void setItems(List<? extends BannerItem> items) {
        if (items == null) throw new NullPointerException("轮播图的列表不能为空");
        baseAdapter.refresh(items);
        banner_recycler_view.scrollToPosition(items.size() * 40);
        banner_indicator.setNumber(items.size(), dotNum);
    }

    /**
     * @param dot
     * @param dotNum 几个引导点
     */
    private void setDotAndNum(boolean dot, final int dotNum) {
        if (dotNum > 2 || dotNum < 1)
            throw new IllegalArgumentException("引导点不能大于二, 且不能小于1,实际值是" + dotNum);
        isDot = dot;
        this.dotNum = dotNum;
        if (isDot) {
            banner_recycler_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        if (baseAdapter.getItems() != null) {
                            int i = layoutManager.findFirstVisibleItemPosition() % baseAdapter.getItems().size();
                            //得到指示器的位置
                            if (dotNum > 1) {
                                banner_indicator.setPosition(i, i + 1 >= baseAdapter.getItems().size() ? 0 : i + 1);
                            } else {
                                banner_indicator.setPosition(i);
                            }
                        }
                    }
                }
            });
        }
    }


    public void setDot(boolean dot) {
        isDot = dot;
        if (isDot) {
            banner_indicator.setVisibility(VISIBLE);
        } else {
            banner_indicator.setVisibility(GONE);
        }
    }

    public void start() {
        if (baseAdapter.getItems().size() > 1) {
            setDotAndNum(true, dotNum);
            scheduledExecutorService.shutdown();
            scheduledExecutorService = Executors.newScheduledThreadPool(1);
            scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    if (!isTouch) {
                        banner_recycler_view.smoothScrollToPosition(layoutManager.findFirstVisibleItemPosition() + 1);
                    }
                }
            }, 2, 4, TimeUnit.SECONDS);
        }


    }


    public interface OnClickItemListener {
        void onItemClick(BannerItem bannerItem, int position);
    }
}

